package com.nolon.flange.tools

import android.Manifest
import android.content.ContentValues
import android.content.Context
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import androidx.core.content.ContextCompat
import org.apache.poi.ss.usermodel.Workbook
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.OutputStream


fun saveXlsFile(mContext: Context, workbook: Workbook, fileName: String): Uri? {
    if (Build.VERSION.SDK_INT < 29) {
        if (!isGranted(mContext)) {
            Log.e("FileSaveUtil", "save to file need storage permission")
            return null
        }
        val destFile = File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
            fileName
        )
        if (!save(destFile, workbook)) return null
        var uri: Uri? = null
        if (destFile.exists()) uri = Uri.parse("file://" + destFile.absolutePath)
        return uri
    } else { //android Q
        val contentUri: Uri =
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                MediaStore.Downloads.EXTERNAL_CONTENT_URI
            } else MediaStore.Downloads.INTERNAL_CONTENT_URI
        //创建ContentValues对象，准备插入数据
        val contentValues = ContentValues()
        contentValues.put(MediaStore.Downloads.MIME_TYPE, "application/vnd.ms-excel") //文件格式
        contentValues.put(MediaStore.Downloads.DATE_TAKEN, System.currentTimeMillis())
        contentValues.put(MediaStore.Downloads.DISPLAY_NAME, fileName) //文件名字
        val fileUri = mContext.contentResolver.insert(contentUri, contentValues) ?: return null
        var outputStream: OutputStream? = null
        try {
            outputStream = mContext.contentResolver.openOutputStream(fileUri)
            if (outputStream != null) {
                workbook.write(outputStream)
//                    outputStream.write(content.toByteArray())
//                    outputStream.flush()
            }
            return fileUri
        } catch (e: Exception) {
            e.printStackTrace()
            mContext.contentResolver.delete(fileUri, null, null) // 失败的时候，删除此 uri 记录
            return null
        } finally {
            try {
                outputStream?.close()
            } catch (e: IOException) {
                // ignore
            }
        }
    }
}

private fun save(file: File, workbook: Workbook): Boolean {
    if (!createFile(file, true)) {
        Log.e("FileSaveUtil", "create or delete file <\$file> failed.")
        return false
    }
    var outStream: FileOutputStream? = null
    var ret: Boolean
    try {
        outStream = FileOutputStream(file)
        workbook.write(outStream)
        ret = true
    } catch (e: Exception) {
        e.printStackTrace()
        ret = false
    } finally {
        try {
            outStream?.close()
        } catch (e: IOException) {
            // ignore
        }
    }
    return ret
}

private fun save(file: File, content: String): Boolean {
    if (!createFile(file, true)) {
        Log.e("FileSaveUtil", "create or delete file <\$file> failed.")
        return false
    }
    var outStream: FileOutputStream? = null
    var ret: Boolean
    try {
        outStream = FileOutputStream(file)
        outStream.write(content.toByteArray())
        outStream.flush()
        ret = true
    } catch (e: Exception) {
        e.printStackTrace()
        ret = false
    } finally {
        try {
            outStream?.close()
        } catch (e: IOException) {
            // ignore
        }
    }
    return ret
}

private fun createFile(file: File?, isDeleteOldFile: Boolean): Boolean {
    if (file == null) return false
    if (file.exists()) {
        if (isDeleteOldFile) {
            if (!file.delete()) return false
        } else return file.isFile
    }
    return if (!createDir(file.parentFile)) false else try {
        file.createNewFile()
    } catch (e: IOException) {
        false
    }
}

private fun createDir(file: File?): Boolean {
    if (file == null) return false
    return if (file.exists()) file.isDirectory else file.mkdirs()
}

private fun isGranted(context: Context): Boolean {
    return Build.VERSION.SDK_INT < Build.VERSION_CODES.M || PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(
        context,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )
}


/**
 * 将Excle表格写入文件中
 *
 * @param workbook
 * @param fileName
 */
fun writeFile(workbook: Workbook?, fileName: String) {
    var outputStream: FileOutputStream? = null
    try {
        outputStream = FileOutputStream(fileName)
        workbook!!.write(outputStream)
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
    } finally {
        try {
            outputStream?.close()
//            workbook?.close()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }
}

/**
 * 保存文本到公共目录(txt文本,其他文件同理)
 * 29 以下，需要提前申请文件读写权限
 * 29及29以上的，不需要权限
 * 保存的文件在 Download 目录下
 *
 * @param mContext 上下文
 * @param content  文本内容
 * @return 文件的 uri
 */
fun saveTextFile(mContext: Context, content: String): Uri? {
    if (TextUtils.isEmpty(content)) return null
    return if (Build.VERSION.SDK_INT < 29) {
        if (!isGranted(mContext)) {
            Log.e("FileSaveUtil", "save to file need storage permission")
            return null
        }
        val destFile = File(
            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
            System.currentTimeMillis().toString() + ".txt"
        )
        if (!save(destFile, content)) return null
        var uri: Uri? = null
        if (destFile.exists()) uri = Uri.parse("file://" + destFile.absolutePath)
        uri
    } else { //android Q
        val contentUri: Uri =
            if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
                MediaStore.Downloads.EXTERNAL_CONTENT_URI
            } else MediaStore.Downloads.INTERNAL_CONTENT_URI
        //创建ContentValues对象，准备插入数据
        val contentValues = ContentValues()
        contentValues.put(MediaStore.Downloads.MIME_TYPE, "text/plain") //文件格式
        contentValues.put(MediaStore.Downloads.DATE_TAKEN, System.currentTimeMillis())
        contentValues.put(MediaStore.Downloads.DISPLAY_NAME, System.currentTimeMillis()) //文件名字
        val fileUri = mContext.contentResolver.insert(contentUri, contentValues) ?: return null
        var outputStream: OutputStream? = null
        try {
            outputStream = mContext.contentResolver.openOutputStream(fileUri)
            if (outputStream != null) {
                outputStream.write(content.toByteArray())
                outputStream.flush()
            }
            fileUri
        } catch (e: Exception) {
            e.printStackTrace()
            mContext.contentResolver.delete(fileUri, null, null) // 失败的时候，删除此 uri 记录
            null
        } finally {
            try {
                outputStream?.close()
            } catch (e: IOException) {
                // ignore
            }
        }
    }
}
